package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.entity.*;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import com.itheima.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Reference
    private SetmealService setmealService;

    @Autowired
    private JedisPool jedisPool;

    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){

        PageResult pageResult = setmealService.findPage(queryPageBean);
        return pageResult;
    }

    //下载图片
    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile multipartFile){
        try {
            //得到原先图片的名字加格式
            String originalFilename = multipartFile.getOriginalFilename();
            //获得格式
            int index = originalFilename.lastIndexOf(".");
            String substring = originalFilename.substring(index);
            //通过uuid获得随机名字
            String fileName = UUID.randomUUID().toString()+substring;
            //加载到七牛云中
            QiniuUtils.upload2Qiniu(multipartFile.getBytes(),fileName);
            //存储到redis中
            Jedis resource = jedisPool.getResource();
            resource.sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
            resource.close();
            //返回结果
            return new Result(true , MessageConstant.PIC_UPLOAD_SUCCESS , fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false , MessageConstant.PIC_UPLOAD_FAIL);
        }
    }

    //添加
    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal , Integer[] checkgroupIds){

        try {
            setmealService.add(setmeal,checkgroupIds);
            //存储到redis中
            Jedis resource = jedisPool.getResource();
            resource.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
            resource.close();
            return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_SETMEAL_FAIL);
        }
    }


}
